class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        if(nums.empty()){return 0;}
        int n=nums.size();
        int l=0,r=0;
        vector<int> markMax(n),markMin(n);
        markMax[0]=nums[0];
        markMin[n-1]=nums[n-1];
        for(int i=1;i<n;i++){
            markMax[i]=max(markMax[i-1],nums[i]);
            markMin[n-1-i]=min(markMin[n-i],nums[n-1-i]);
        }
        for(int i=n-1;i>=0;i--){
            if(nums[i]<markMax[i]){r=i;break;}
        }
        for(int i=0;i<n;i++){
            if(nums[i]>markMin[i]){l=i;break;}
        }
        if(l==0&&r==0){return 0;}
        return r-l+1;
    }
};

